<template>
<div class="Row_content" style="width:890px;">
  <Form
      inline
      ref="formValidate"
      :model="formValidate"
      :rules="ruleValidate"
      :label-width="130">
      <FormItem label="活动名称:" prop="keyName">
        <Input v-model="formValidate.keyName" placeholder="请输入" class='input-wid' :maxlength="20" @on-keyup='filterSpace' @on-blur="filterSpace"></Input>
      </FormItem>
      <FormItem label="适用产品:" prop="categorys" v-show="activityIntegerType == '4'">
        <Select v-model="formValidate.categorys" multiple>
          <Option v-for="(item, index) in categoryList"
            :value="item.value"
            :key="index">
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <div style="display: inline-block; width:430px;" v-show="activityIntegerType == '5'"></div>
      <FormItem label="开始时间:" prop="activityStart">
        <DatePicker :value="formValidate.activityStart" format="yyyy-MM-dd HH:mm:ss" :editable="false" type="datetime" placeholder="请选择" style="width: 280px" @on-change="activityStartChange" :options="activityStartOptions"></DatePicker>
      </FormItem>
      <FormItem label="结束时间:" prop="activityEnd">
        <DatePicker :value="formValidate.activityEnd" format="yyyy-MM-dd HH:mm:ss" :editable="false" type="datetime" placeholder="请选择" style="width: 280px" @on-change="activityEndChange" :options="activityEndOptions"></DatePicker>
      </FormItem>
      <FormItem label="面向渠道:" prop="channel" v-show="activityIntegerType == '4'">
        <Select v-model="formValidate.channel" multiple>
          <Option v-for="(item, index) in channelList"
            :value="item.value"
            :key="index">
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="面向品牌:" prop="brandIds" v-show="activityIntegerType == '4'">
        <Select v-model="formValidate.brandIds" multiple>
          <Option v-for="(item, index) in brandList"
            :value="item.brandId"
            :key="index">
            {{ item.brandName }}
          </Option>
        </Select>
      </FormItem>
      <template v-if="activityIntegerType == '4'">
        <FormItem align="right" :rules="[{required: true, message: '兑换比例不能为空', trigger: 'blur'}]" :label="'V' + level.memberLevel + '等级:'" :prop="'memberLevelList.'+index+'.rate'" v-for="(level, index) in formValidate.memberLevelList" :key="'V' + index">
          <span style="padding-right:10px;">1:</span><Input v-model="level.rate" style="width:90%;" class='input-wid' :maxlength="4" @on-blur="levalBlur(index)" @on-keyup="filterNum(index)"></Input>
        </FormItem>
      </template>
      <template v-if="activityIntegerType == '5'">
        <FormItem :rules="[{required: true, message: '积分不能为空', trigger: 'blur'}]"  :label="message.label + ':'" :prop="'memberMessageList.'+index+'.val'" v-for="(message, index) in formValidate.memberMessageList" :key="index">
          <Input v-model="message.val" class='input-wid' :maxlength="5" @on-blur="levalBlur2(index)" @on-keyup="filterNum2(index)"></Input><span style="position:absolute;right:-30px; top:0;">积分</span>
        </FormItem>
      </template>
      <FormItem  v-if="activityIntegerType == '5'">
      <Button class="system-submit-btn" @click="showTagModel">添加标签 <Icon type="md-add" /></Button>
      </FormItem>
      <FormItem style="width: 830px" v-if="activityIntegerType == '5' && definedTagList.length > 0">
        <div style="border:1px solid #DCDEE2; border-radius: 3px; padding:20px; width:700px;">
          <Tag closable color="default" style="height:32px; line-height:32px; padding:0 10px;" v-for="(tag, index) in definedTagList" @on-close="removeTag(tag)" :key="index">{{tag.itemName}}</Tag>
        </div>
      </FormItem>
      <FormItem label="活动说明:" style="width: 830px">
        <Input v-model="formValidate.explains"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          :maxlength="200"
          placeholder="请输入"
          style="width:700px"></Input>
      </FormItem>
      <FormItem class="form-btn"
              style="margin-top: 5px;">
      <Button type="primary"
              class="system-submit-btn"
              @click="handleSubmit"
              >确定</Button>
      <Button class="system-submit-btn"
        @click="handleReset"
        style="margin-left: 8px">取消</Button>
    </FormItem>
  </Form>
  <Modal title="添加标签"
             width='400'
             v-model="tagModelVisible" class="createpointtag">
        <Form :model="tagForm"
              ref="tagValidate"
              :label-width="0"
              :rules="tagValidate">
          <FormItem label=" " prop="tagName">
            <Input v-model="tagForm.tagName" :maxlength="10" @on-keyup='filterTagSpace' @on-blur="filterTagSpace" />
          </FormItem>
        </Form>
        <div slot="footer"
             class="foot">
          <Button class="btn"
                  @click='handleTagCancel'>取消</Button>
          <Button type="primary"
                  class="btn"
                  @click="handleTagSubmit">确认</Button>
        </div>
      </Modal>
</div>
</template>

<script>
import { routeEqual } from '@/libs/util'
import { mapState } from 'vuex'
import { getMemberLevelList } from '@/api/member/index.js'
import { savePoint, queryPoint } from '@/api/market/point.js'
import { getBrandList, saveTag, delTag, getTagList } from '@/api/merchant.js'
import enumsMixin from '../enums.js'
export default {
  name: 'market_point_edit',
  mixins: [enumsMixin],
  data () {
    return {
      activityIntegerType: '',
      activityIntegerId: '',
      formValidate: {
        activityIntegerId: '',
        keyName: '',
        categorys: [],
        channel: [],
        brandIds: [],
        memberLevelList: [],
        memberMessageList: [],
        activityStart: '',
        activityEnd: '',
        explains: ''
      },
      activityStartOptions: {},
      activityEndOptions: {},
      ruleValidate: {
        keyName: { required: true, message: '请填写活动名称', trigger: 'blur' },
        activityStart: {
          required: true,
          trigger: 'change',
          message: '请选择开始时间'
        },
        activityEnd: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formValidate.activityEnd).getTime()) {
              callback(new Error('请选择结束时间'))
            } else if (new Date(this.formValidate.activityStart).getTime() > new Date(this.formValidate.activityEnd).getTime()) {
              callback(new Error('开始时间不能大于结束时间'))
            } else {
              callback()
            }
          }
        },
        categorys: { required: true, message: '请选择适用产品' },
        channel: { required: true, message: '请选择面向渠道' },
        brandIds: { required: true, message: '请选择面向品牌' }
      },
      brandList: [],
      submitLock: false,
      tagModelVisible: false,
      definedTagList: [],
      tagValidate: {
        tagName: { required: true, message: '标签名称不能为空', trigger: 'blur' }
      },
      tagForm: {
        tagName: ''
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.id !== to.params.id) {
        vm.id = to.params.id
        vm.getDetail()
      }
    })
  },
  mounted () {
    this.activityIntegerType = this.$route.params.type
    if (parseInt(this.$route.params.type) === 5) {
      this.getTagList()
    }
    this.getDetail()
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    })
  },
  watch: {
    tagModelVisible (val) {
      if (!val) {
        this.$refs.tagValidate.resetFields()
      }
    }
  },
  methods: {
    filterSpace () {
      this.formValidate.keyName = this.formValidate.keyName.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/, '')
    },
    filterTagSpace () {
      this.tagForm.tagName = this.tagForm.tagName.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/, '')
    },
    filterNum (index) {
      let val = this.formValidate.memberLevelList[index].rate
      if (val !== '' && val.substring(0, 1) === '.') {
        val = ''
      }
      val = val.replace(/^0*(0\.|[1-9])/, '$1')
      val = val.replace(/[^\d.]/g, '')
      val = val.replace(/\.{2,}/g, '.')
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      val = val.replace(/^(-)*(\d+)\.(\d).*$/, '$1$2.$3')
      if (val.length === 2 && val === '00') {
        val = '0'
      }
      this.formValidate.memberLevelList[index].rate = val
    },
    levalBlur (index) {
      let val = this.formValidate.memberLevelList[index].rate
      if (val.indexOf('.') === val.length - 1) {
        val = val.substring(0, val.length - 1)
      }
      this.formValidate.memberLevelList[index].rate = val
    },
    filterNum2 (index) {
      let val = this.formValidate.memberMessageList[index].val
      val = val.replace(/\D/g, '')
      if (val.length > 1 && val.substring(0, 1) === '0') {
        val = '0'
      }
      this.formValidate.memberMessageList[index].val = val
    },
    levalBlur2 (index) {
      let val = this.formValidate.memberMessageList[index].val
      val = val.replace(/\D/g, '')
      this.formValidate.memberMessageList[index].val = val
    },
    activityStartChange (time) {
      this.formValidate.activityStart = time
      this.activityEndOptions = {
        disabledDate (date) {
          return date.valueOf() < new Date(time.split(' ')[0]).getTime() - 24 * 3600 * 1000
        }
      }
    },
    activityEndChange (time) {
      this.formValidate.activityEnd = time
      this.activityStartOptions = {
        disabledDate (date) {
          return date.valueOf() > new Date(time).getTime()
        }
      }
    },
    getDetail () {
      this.activityIntegerType = this.$route.params.type
      this.activityIntegerId = this.$route.params.id
      queryPoint({
        activityIntegerId: this.activityIntegerId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          const active = result.data.rewardPointsActivity
          this.formValidate.keyName = active.keyName
          this.formValidate.activityIntegerId = active.activityIntegerId
          this.formValidate.activityStart = active.activityStart
          this.formValidate.activityEnd = active.activityEnd
          this.formValidate.explains = active.explains
          if (result.data.rewardPointsActivity.activityIntegerType === 4) {
            this.ruleValidate.categorys.required = true
            this.ruleValidate.channel.required = true
            this.ruleValidate.brandIds.required = true
            this.formValidate.categorys = active.categorys.split(',')
            this.formValidate.channel = active.channel.split(',')
            this.formValidate.brandIds = active.brandIds.split(',')
            getMemberLevelList({
              merchantId: this.merchantId
            }).then(res => {
              if (res.data.status === 200) {
                let list = res.data.data.map((item, i) => {
                  let memberLevel = result.data.rewardPointsRule.filter(config => {
                    return config.configKey === 'V' + item.memberLevel
                  })
                  item.rate = memberLevel.length ? memberLevel[0].configValue : ''
                  item.index = i
                  return item
                })
                this.formValidate.memberLevelList = list
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            })
            getBrandList({
              merchantId: this.merchantId
            }).then(res => {
              if (res.data.status === 200) {
                this.brandList = res.data.data
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            }).catch(err => {
              this.$Message.error(`${err}`)
            })
          } else {
            this.ruleValidate.categorys.required = false
            this.ruleValidate.channel.required = false
            this.ruleValidate.brandIds.required = false
            this.formValidate.memberMessageList = JSON.parse(JSON.stringify(this.memberMessageList)).map(item => {
              let memberMessage = result.data.rewardPointsRule.filter(config => {
                return config.configKey === item.key
              })
              item.val = memberMessage.length ? memberMessage[0].configValue : ''
              return item
            })
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    handleSubmit () {
      this.$refs.formValidate.validate(val => {
        if (val) {
          const formValidate = this.formValidate
          if (new Date(formValidate.activityStart).getTime() > new Date(formValidate.activityEnd).getTime()) {
            this.$Message.error('开始时间不能大于结束时间')
            return
          }
          const params = {
            rewardPointsActivity: {
              merchantId: this.merchantId,
              activityIntegerId: formValidate.activityIntegerId,
              activityIntegerType: parseInt(this.activityIntegerType),
              keyName: formValidate.keyName,
              activityStart: formValidate.activityStart,
              activityEnd: formValidate.activityEnd,
              explains: formValidate.explains,
              operatorId: this.userId,
              operatorName: this.userName
            }
          }
          if (parseInt(this.activityIntegerType) === 4) {
            let ruleobj = []
            formValidate.memberLevelList.forEach(item => {
              ruleobj.push({
                configKey: 'V' + item.memberLevel,
                configValue: item.rate
              })
            })
            params.rewardPointsActivity.categorys = formValidate.categorys.join(',')
            params.rewardPointsActivity.brandIds = formValidate.brandIds.join(',')
            params.rewardPointsActivity.channel = formValidate.channel.join(',')
            params.rewardPointsRule = ruleobj
          } else {
            let ruleobj = []
            formValidate.memberMessageList.forEach(item => {
              ruleobj.push({
                configKey: item.key,
                configValue: item.val
              })
            })
            params.rewardPointsRule = ruleobj
          }
          if (this.submitLock) {
            return
          }
          this.submitLock = true
          savePoint(params).then(res => {
            this.submitLock = false
            const result = res.data || {}
            if (result.status === 200) {
              this.$Message.success('编辑成功')
              this.handleReset()
            } else {
              this.$Message.error(`${result.error}`)
            }
          }).catch(err => {
            this.submitLock = false
            this.$Message.error(`${err}`)
          })
        }
      })
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'market_point_list'
        })
      })
    },
    getTagList () {
      getTagList({
        merchantId: this.merchantId
      }).then(res => {
        if (res.data.status === 200) {
          this.definedTagList = res.data.data
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    removeTag (item, index) {
      delTag({
        merchantId: this.merchantId,
        itemName: item.itemName
      }).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('删除标签成功')
          this.getTagList()
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    showTagModel () {
      this.tagModelVisible = true
    },
    handleTagCancel () {
      this.tagModelVisible = false
    },
    handleTagSubmit () {
      this.$refs.tagValidate.validate((valid) => {
        if (valid) {
          saveTag({
            merchantId: this.merchantId,
            itemName: this.tagForm.tagName,
            dictCategory: '',
            creatorId: this.userId,
            creatorName: this.userName
          }).then(res => {
            if (res.data.status === 200) {
              this.$Message.success('添加标签成功')
              this.getTagList()
              this.tagModelVisible = false
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    }
  }
}
</script>
